package net.easyjava.test.aws;

import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.sqs.model.Message;

import java.util.List;

/**
 * Created by wxnacy on 16/11/24.
 */
public class User2Demo {
    public static final String TOPIC_ARN2 = "arn:aws:sns:us-east-1:053227996260:topic-2";
    public static final String QUEUE_1 = "queue-1";
    public static final String QUEUE_URL_1 = "https://sqs.us-east-1.amazonaws.com/053227996260/queue-1";

    public static void main(String[] args) {
        System.out.println("User2等待接收上传秘钥:");
        SQSDemo sqsDemo = new SQSDemo();
        S3Demo s3Demo = new S3Demo();
        SNSDemo snsDemo = new SNSDemo();
        System.out.println("接受中...");

        while(true){
            List<Message> messages = sqsDemo.receiveMessageFromTopic(QUEUE_URL_1);
            if(messages.size()>0 && messages.get(0) !=null){
                Message message = messages.get(0);
                String body = message.getBody();
                JSONObject data = JSONObject.parseObject(body);
                System.out.printf("接收到秘钥:       %s\n",data.get("Message"));
                System.out.println("验证通过并开始上传文件");
                System.out.println("上传中...");
                String key = s3Demo.putObject("test/"+System.currentTimeMillis());
                try{
                    sqsDemo.delMsg(QUEUE_URL_1,message.getReceiptHandle());
                }catch(Exception e){
                    e.printStackTrace();
                }
                System.out.println("文件上传完毕,并将地址通知给User1");
                System.out.println("地址:     "+key);
                snsDemo.sendMessageToTopic(TOPIC_ARN2,key);
                System.out.println("操作完毕,等待下次接收秘钥");
                System.out.println("接受中...");
            }


            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }



}
